package com.test.tm.controller;

import com.test.tm.service.TmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
public class TmController {

    @Autowired
    TmService service;

    AtomicInteger ai = new AtomicInteger(0);

    /**
     * 调用AT自动事务
     *
     * @param name - 传入参数
     * @return String (success)
     */
    @GetMapping("/insert-at")
    public String insertAt(@RequestParam String name) {
        Map<String, String> params = new HashMap<>(2);
        params.put("name", name);
        params.put("name", ai.getAndIncrement() + "");
        return service.insertAt(params);
    }

    @GetMapping("/update-at1")
    public String updateAt1(@RequestParam String name1,@RequestParam String name2) {
        Map<String, String> params = new HashMap<>(2);
        params.put("name1", name1);
        params.put("name2", name2);
        return service.updateAt1(params);
    }

    @GetMapping("/update-at2")
    public String updateAt2(@RequestParam String name1,@RequestParam String name2) {
        Map<String, String> params = new HashMap<>(2);
        params.put("name1", name1);
        params.put("name2", name2);
        return service.updateAt2(params);
    }

    /**
     * 调用TCC手工分布式事务
     *
     * @param name - 入参
     * @return String
     */
    @GetMapping("/insert-tcc")
    public String insertTcc(@RequestParam String name) {
        Map<String, String> params = new HashMap<>(2);
        params.put("name", name);
        params.put("name", ai.getAndIncrement() + "");
        return service.insertTcc(params);
    }

    @GetMapping("/update-tcc")
    public String updateTcc(@RequestParam String id,@RequestParam String name) {
        Map<String, String> params = new HashMap<>(2);
        params.put("id", id);
        params.put("name", name);
        return service.updateTcc(params);
    }

}
